package com.alpha.service.config;

import com.alpha.core.http.AlphaHttpContext;
import com.alpha.core.http.HttpConstants;
import com.alpha.core.utils.JsonUtil;
import com.alpha.service.context.AlphaApplicationContext;
import com.google.common.collect.ImmutableMap;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

/**
 * openfeign 拦截器
 *
 * @author chenruwan
 * @since 2022-01-01
 */
@Configuration
public class FeignRequestInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        Map<String, Object> context = AlphaHttpContext.getContext();
        if (context != null) {
            requestTemplate.header(HttpConstants.CLAIMS, JsonUtil.toString(context));
            return;
        }

        requestTemplate.header(HttpConstants.CLAIMS, JsonUtil.toString(ImmutableMap.builder()
                .put(HttpConstants.CLAIM_USER_NAME, AlphaApplicationContext.getApplicationName())
                .build()));
    }
}
